//
//  ViewController.m
//  SocketServer
//
//  Created by 袁飞霞 on 16/5/17.
//  Copyright © 2016年 cn.sophietobeabetterone. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"

@interface ViewController () <GCDAsyncSocketDelegate>

@property (weak) IBOutlet NSTextField *portNumField;
@property (nonatomic, strong) GCDAsyncSocket *serverSocket;
@property (nonatomic, strong) NSMutableArray *clients;

@end

@implementation ViewController

- (IBAction)startAction:(id)sender {
    [self.serverSocket acceptOnPort:self.portNumField.integerValue error:nil];
}

#pragma mark - socket 代理协议

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
    [self.clients addObject:newSocket];
    
    // 让这个socket进入准备读取数据的状态
    [newSocket readDataWithTimeout:-1 tag:0];
    
    NSString *welcomeStr = @"Welcome to heima!";
    [newSocket writeData:[welcomeStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString *contentStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    // socket进入准备读取数据的状态时,默认只读取下一次.所以每次读取到数据之后,都要再次进入准备读取数据的状态
    [sock readDataWithTimeout:-1 tag:0];
    
    NSLog(@"%@", contentStr);
}

#pragma mark 懒加载

- (GCDAsyncSocket *)serverSocket {
    if (!_serverSocket) {
        _serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    return _serverSocket;
}

- (NSMutableArray *)clients {
    if (_clients == nil) {
        _clients = [[NSMutableArray alloc] init];
    }
    return _clients;
}

@end












